package hook

import (
	"acs/comet/config"
	"time"

	"gitee.com/JMArch/go-plugins/registry/etcdv3"
	"gitee.com/JMArch/go-plugins/selector/weights"
	"gitee.com/JMArch/go-plugins/transport/tcp"
	"gitee.com/JMArch/micro"
	client "gitee.com/JMArch/micro/client"
	"gitee.com/JMArch/micro/registry"
	"github.com/sunreaver/logger"
)

type Hook struct {
	RegisterNotice   func(self *Hook, info interface{})
	UnRegisterNotice func(self *Hook, info interface{})

	rpcClient BroadcastService
	cfg       config.HookConfig
}

func NewHook(cfg config.HookConfig) *Hook {
	loggerHook = logger.GetSugarLogger("hook.log")

	loggerHook.Infow("newhook", "cfg", cfg)

	tmp := &Hook{
		RegisterNotice:   empty,
		UnRegisterNotice: empty,

		rpcClient: newRPCClient(cfg),
		cfg:       cfg,
	}

	if cfg.Register {
		tmp.RegisterNotice = defaultRegisterNotice
	}
	if cfg.UnRegister {
		tmp.UnRegisterNotice = defaultUnRegisterNotice
	}
	return tmp
}

func newRPCClient(cfg config.HookConfig) BroadcastService {
	if len(cfg.EtcdHosts) == 0 || len(cfg.ServiceName) == 0 {
		return nil
	}
	s := micro.NewService(
		micro.Client(client.NewClient(
			client.ContentType("application/jmtext"), // 选择使用thrift协议，相应的还有 application/jmtext
			client.DialTimeout(time.Second*5),        // 连接超时设置，默认5秒
			client.RequestTimeout(time.Second*10),    // 请求超时设置，默认5秒
			client.Retries(2),                        // 请求失败、出错后重试次数，默认1次。重试次数最好大于0。
			client.PoolTTL(time.Minute),              // 连接闲置缓存时间，默认1分钟
			client.PoolSize(100),                     // 默认缓存连接数，默认100个
		)),
		micro.Name("acscomet.notify.client"),  // 客户端名称
		micro.Transport(tcp.NewTransport()),   // 选用tcp连接，默认http
		micro.Selector(weights.NewSelector()), // 使用权重模式负载均衡，默认随机模式
		micro.Registry(
			etcdv3.NewRegistry(
				// 设置服务注册地址，默认为：localhost:default_port
				// default_port视各服务注册方式而定
				registry.Addrs(cfg.EtcdHosts...),
			), // etcdv3
		), // 选择服务注册方式，默认consul。
	)
	return NewBroadcastService(cfg.ServiceName, s.Client())
}
